﻿using Shop.Model.DB;
using Shop.Model.Spec;
using Shop.Model.SpecGroup;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class GoodsSpecRepository : ShopBaseRepository<DBGoodsSpec, long>, IGoodsSpecRepository
    {
        public GoodsSpecRepository (ISqlClientFactory factory) : base(factory)
        {
        }
        public long Add (GoodsSpecAddDto dto)
        {
            DBGoodsSpec add = dto.ConvertMap<GoodsSpecAddDto, DBGoodsSpec>();
            add.Id = IdentityHelper.CreateId();
            base.Insert(add);
            return add.Id;
        }
        public void SetSort (Dictionary<long, int> sorts)
        {
            if (!base.Update(sorts.ConvertAll(a => new DBGoodsSpec
            {
                Id = a.Key,
                Sort = a.Value
            }), "Sort"))
            {
                throw new ErrorException("shop.spec.group.set.fail");
            }
        }
        public SpecDto[] GetsSpec (long[] ids)
        {
            return base.Join<DBGoodsSpecGroup, SpecDto>((a, b) => a.GroupId == b.Id && ids.Contains(a.Id), (a, b) => new SpecDto
            {
                GroupId = a.GroupId,
                GroupName = b.GroupName,
                SpecId = b.Id,
                SpecName = a.SpecName
            });
        }
        public GoodsSpecDto[] Gets (long goodsId)
        {
            return base.Gets<GoodsSpecDto>(a => a.GoodsId == goodsId, "Sort");
        }
    }
}
